const checkValue = (obj: any, key: string[]): any => {
    if (!key?.[0]) {
        return obj;
    }
    if (typeof obj[key[0]] === 'object') {
        return checkValue(obj[key[0]], key.slice(1));
    }
    if (key.length > 1) {
        return undefined;
    }
    return obj[key[0]];
};

export const setValue = (object: any = {}, keys: string, value: any) => {
    const keyArray = keys.replace(/\[['"]?(.*?)['"]?\]/g, '.$1')?.split('.')
    let temp = object;
    for (let i = 0; i < keyArray.length - 1; i++) {
        const currentKey = keyArray[i];
        const nextKey = keyArray[i + 1];
        const isNumberKey = /^\d+$/.test(currentKey);
        const key = isNumberKey ? Number(currentKey) : currentKey;
        const nextIsNumberKey = /^\d+$/.test(nextKey);
        if (!Object.prototype.hasOwnProperty.call(temp, key) || temp[key] === null || temp[key] === undefined) {
            temp[key] = nextIsNumberKey ? [] : {};
        } else {
            if (nextIsNumberKey && !Array.isArray(temp[key])) {
                temp[key] = [];
            } else if (!nextIsNumberKey && Array.isArray(temp[key])) {
                const newObj: any = {};
                temp[key].forEach((item: any, idx: number) => {
                    newObj[idx] = item;
                });
                temp[key] = newObj;
            }
        }
        temp = temp[key];
    }
    const lastKey = keyArray[keyArray.length - 1];
    const isLastNumberKey = /^\d+$/.test(lastKey);
    const finalKey = isLastNumberKey ? Number(lastKey) : lastKey;
    temp[finalKey] = value;
};

export const getValue = (object = {}, keys: string): any => {
    const keyArray = keys.replace(/\[['"]?(.*?)['"]?\]/g, '.$1')?.split('.');
    return checkValue(object, keyArray);
};